package com.db.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class WorkerThread implements Runnable {

    public static void startPool(int suggestedPort) throws IOException {
        Parameter.setPort(suggestedPort);
        Parameter.print();
        int port = Parameter.getPort();
        int workers = Parameter.getWorkers();
        int timeout = Parameter.getTimeout(); 
        
        ExecutorService service = Executors.newFixedThreadPool(workers);
        
        boolean working = true;
        ServerSocket srvSocket = new ServerSocket(port, 1000);
        while (working) {
        	try {
        		Socket socket = srvSocket.accept();
        		socket.setSoTimeout(timeout);
        		service.submit(new WorkerThread(socket));
        	} catch (SocketTimeoutException e) {
        		System.out.println(e.getMessage());
        	}
        }
        
        srvSocket.close();
    }

	private Socket socket;
    
    public WorkerThread(Socket socket) {
    	this.socket = socket;
    }

    public void run() {
    	try {
			new Worker().handleRequest(socket);
    	} catch (SocketTimeoutException e) {
    		System.out.println(e.getMessage());
		} catch (IOException e) {
			System.out.println(e.getMessage());
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
    }
}